package com.after.saas.user.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.after.saas.user.manager.UserManager;
import com.after.saas.user.model.User;
import com.after.saas.user.mapper.UserMapper;
import com.after.saas.user.service.UserService;
import com.after.saas.user.utils.UserUtil;
import com.after.saas.common.model.bo.UserBO;
import com.after.saas.common.model.query.UserQuery;
import com.after.saas.common.model.vo.UserVO;
import com.after.saas.common.utils.ListUtil;
import com.after.saas.common.utils.PasswordUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author hjchen
 * @since 2021-07-17
 */

@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserService userService;

    @Autowired
    private UserManager userManager;

    @Override
    public Boolean batchSave(List<UserBO> boList) {
        List<User> users = ListUtil.copyList(boList, User.class);
        users.forEach(user -> {
            PasswordUtil.HashPassword hashPassword = PasswordUtil.generate(Optional.ofNullable(user.getPassword()).orElse("123456"));
            user.setPassword(hashPassword.password);
            user.setSalt(hashPassword.salt);
        });
        return userService.saveBatch(users);
    }

    @Override
    @Cacheable(value = "saas:user", key = "#query.username+'_' + #query.id")
    public UserVO findOne(UserQuery query) {
        return userManager.findOne(query);
    }

    @Override
    @Cacheable(value = "saas:user", key = "#id")
    public UserVO findById(Long id) {
        UserVO userVO = new UserVO();
        User user = getById(id);
        if (ObjectUtil.isNotEmpty(user)) {
            BeanUtils.copyProperties(user, userVO);
        }
        return userVO;
    }

    @Override
    public Page<UserVO> queryByPage(UserQuery query) {
        Page<User> page = page(new Page<>(query.getPage(), query.getSize()), UserUtil.buildWrapper(query));
        Page<UserVO> userVOPage = new Page<>(query.getPage(), query.getSize(), page.getTotal());
        userVOPage.setRecords(ListUtil.copyList(page.getRecords(), UserVO.class));
        return userVOPage;
    }

    @Override
    @Cacheable(value = "saas:user")
    public List<UserVO> queryAll(UserQuery query) {
        return ListUtil.copyList(list(UserUtil.buildWrapper(query)), UserVO.class);
    }

}
